/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.webos.java.base.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import org.webos.java.root.Log;

/**
 *
 * @author Kostya
 */
public class CryptoUtil {
    private static byte[] salt = {0x34, 0x57, 0x12, 0x03, 0x55, 0x05, 0x61, 0x07};
    private static int retries = 10;

    public static String encode(String password, String value){
        try {
            PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
            PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, retries);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
            SecretKey key = keyFactory.generateSecret(keySpec);
            Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
            cipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec);
            byte[] cipherText = cipher.doFinal(value.getBytes("utf-8"));
            return Base64.encode(cipherText);
        } catch (Throwable t) {
            Log.error(null, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
        return "";
    }

    public static String decode(String password, String value){
        try {
            PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
            PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, retries);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
            SecretKey key = keyFactory.generateSecret(keySpec);
            Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
            cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec);
            byte[] cipherText = cipher.doFinal(Base64.decode(value));
            return new String(cipherText, "utf-8");
        } catch (Throwable t) {
            Log.error(null, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
        return "";
    }
}
